/**
 * ...
 * @author Krzysztof Rozalski
 */

package hapi.facebook;

import hapi.facebook.externs.Facebook;
import hapi.facebook.externs.FacebookApiException;
import hapi.log.LogLevel;

class FacebookAdapter {
	
	var facebook:Facebook;
	public var config(default, null):FacebookAdapterConfig;
	var loginUrl:String;
	var logoutUrl:String;
	var session:FacebookSession;
	var currentUser:FacebookUserBasicData;

	public function new(config:FacebookAdapterConfig) {
		this.config = config;
		facebook = new Facebook(config.asPhpArray());
	}
	
	public function hasSession():Bool {
		return session != null;
	}
	
	public function getSession():FacebookSession {
		if (!hasSession()) requestSession();
		return session;
	}
	
	public function redirectToLogin() {
		php.Lib.println("<script type='text/javascript'>top.location.href = '"+getLoginUrl()+"';</script>");
	}
	
	public function getCurrentUserId():String {
		return facebook.getUser();
	}
	
	public function getLoginUrl():String {
		if ( loginUrl == null ) requestLoginUrl();
		return loginUrl;
	}
	
	public function getLogoutUrl():String {
		if ( logoutUrl == null ) requestLogoutUrl();
		return logoutUrl;
	}
	
	public function getCurrentUserData():FacebookUserBasicData {
		if (currentUser == null) requestCurrentUser();
		return currentUser;
	}
	
	public function restApi(params:Hash<Dynamic>):Hash<Dynamic> {
		var paramsArray = hapi.php.Lib.associativeArrayOfHash(params, true);
		var data = facebook.api(paramsArray);
		return hapi.php.Lib.hashOfAssociativeArray(data, true);
	}
	
	public function graph(path:String , ?params:Hash<Dynamic>=null, ?method = "GET"):Hash<Dynamic> {
		var paramsArray = hapi.php.Lib.associativeArrayOfHash(params, true);
		var data:Dynamic = facebook.api(path, method, paramsArray);
		return hapi.php.Lib.hashOfAssociativeArray(data, true);
	}
	
	public function fql(query:String):Hash<Dynamic> {
		var hash:Hash<Dynamic> = new Hash<Dynamic>();
		hash.set("method", "fql.query");
		hash.set("query", query);
		var args = php.Lib.associativeArrayOfHash(hash);
		var data:Dynamic = facebook.api(args);
		var result:Hash<Dynamic> = hapi.php.Lib.hashOfAssociativeArray(data, true);
		return result;
	}
	
	public function fqlMultiquery(queries:Array<String>):Hash<Dynamic> {
		var queriesArg = new Hash<Dynamic>();
		for ( i in 0...queries.length ) {
			queriesArg.set(Std.string(i + 1), queries[i]);
		}
		var args:Hash<Dynamic> = new Hash<Dynamic>();
		args.set("method", "fql.multiquery");
		args.set("queries", php.Lib.associativeArrayOfHash(queriesArg));
		var data:Dynamic = facebook.api(php.Lib.associativeArrayOfHash(args));
		var result:Hash<Dynamic> = hapi.php.Lib.hashOfAssociativeArray(data, true);
		return result;
	}
	
	function requestSession() {
		try {
			var phpSession = facebook.getSession();
			if (phpSession != null) session = new FacebookSession(cast phpSession);
			else throw new FacebookException("session could not be initialized");
		}catch (e:FacebookApiException) {
			trace(e.getTrace(), LogLevel.error);
			trace(e.getResult() + " " + e.getMessage(), LogLevel.error);
			throw new FacebookException("session could not be initialized");
		}
	}
	
	function requestCurrentUser() {
		if ( ! hasSession() ) requestSession();
		var userData = graph("/me");
		currentUser = new FacebookUserBasicData(userData);
	}
	
	function requestLoginUrl() {
		loginUrl = facebook.getLoginUrl(config.getUrlsConfig());
	}
	
	function requestLogoutUrl() {
		logoutUrl = facebook.getLogoutUrl(config.getUrlsConfig());
	}
}